package com.roamer.audition.web.security.handler;

import cn.hutool.json.JSONUtil;
import com.roamer.rest.IErrorCode;
import com.roamer.rest.RestResult;
import com.roamer.rest.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证/Login失败处理器
 *
 * @author roamer
 * @version v1.0
 * @date 2020/3/9 16:41
 */
public class AuthFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ResultCode.ErrorCode errorCode = IErrorCode.C40100;
        if (exception instanceof InternalAuthenticationServiceException || exception instanceof BadCredentialsException) {
            errorCode = IErrorCode.C40101;
        } else if (exception instanceof DisabledException) {
            errorCode = IErrorCode.C40102;
        } else if (exception instanceof LockedException) {
            errorCode = IErrorCode.C40103;
        } else if (exception instanceof AccountExpiredException) {
            errorCode = IErrorCode.C40104;
        }
        response.getWriter().write(JSONUtil.toJsonStr(RestResult.failure(errorCode)));
    }
}
